import { BaseEntity } from './BaseEntity';
import { Item } from './Item';

/**
 * 任务实体类
 */
export class Task extends BaseEntity {
    /** 任务名称 */
    public name: string;
    
    /** 任务描述 */
    public description: string;
    
    /** 任务类型 */
    public type: TaskType;
    
    /** 任务状态 */
    public status: TaskStatus;
    
    /** 任务目标 */
    public targets: TaskTarget[];
    
    /** 任务奖励 */
    public rewards: TaskReward[];
    
    /** 任务要求 */
    public requirements: TaskRequirements;
    
    /** 任务进度 */
    public progress: Record<string, number>;
    
    /** 任务开始时间 */
    public startTime?: Date;
    
    /** 任务完成时间 */
    public completeTime?: Date;
    
    /** 任务截止时间 */
    public deadline?: Date;
    
    /** 任务优先级 */
    public priority: TaskPriority;
    
    /** 任务标签 */
    public tags: string[];
    
    /** 是否为主线任务 */
    public isMainQuest: boolean;
    
    /** 是否可重复 */
    public isRepeatable: boolean;
    
    /** 重复类型 */
    public repeatType: RepeatType;
    
    /** 任务数据 */
    public data: TaskData;

    constructor(id?: string) {
        super(id);
        
        this.name = '';
        this.description = '';
        this.type = TaskType.击杀;
        this.status = TaskStatus.未开始;
        this.targets = [];
        this.rewards = [];
        this.requirements = {
            level: 1,
            attributes: {},
            completedTasks: []
        };
        this.progress = {};
        this.priority = TaskPriority.NORMAL;
        this.tags = [];
        this.isMainQuest = false;
        this.isRepeatable = false;
        this.repeatType = RepeatType.NONE;
        this.data = {};
    }

    /**
     * 创建任务
     */
    public static create(config: TaskCreateConfig): Task {
        const task = new Task(config.id);
        
        task.name = config.name;
        task.description = config.description || '';
        task.type = config.type || TaskType.击杀;
        task.status = config.status || TaskStatus.NOT_STARTED;
        task.targets = config.targets || [];
        task.rewards = config.rewards || [];
        task.requirements = config.requirements || {
            level: 1,
            attributes: {},
            completedTasks: []
        };
        task.progress = config.progress || {};
        task.deadline = config.deadline;
        task.priority = config.priority || TaskPriority.NORMAL;
        task.tags = config.tags || [];
        task.isMainQuest = config.isMainQuest || false;
        task.isRepeatable = config.isRepeatable || false;
        task.repeatType = config.repeatType || RepeatType.NONE;
        task.data = config.data || {};
        
        return task;
    }

    /**
     * 开始任务
     */
    public start(): StartResult {
        if (this.status !== TaskStatus.NOT_STARTED) {
            return {
                success: false,
                message: '任务已经开始或已完成'
            };
        }

        this.status = TaskStatus.IN_PROGRESS;
        this.startTime = new Date();
        
        // 初始化进度
        this.targets.forEach((target, index) => {
            const progressKey = target.id || `target_${index}`;
            this.progress[progressKey] = 0;
        });

        this.updateEntity();

        return {
            success: true,
            message: `任务 "${this.name}" 已开始`
        };
    }

    /**
     * 更新任务进度
     */
    public updateProgress(targetId: string, amount: number): ProgressResult {
        if (this.status !== TaskStatus.IN_PROGRESS) {
            return {
                success: false,
                message: '任务未在进行中',
                isCompleted: false,
                currentProgress: this.progress[targetId] || 0
            };
        }

        const target = this.targets.find(t => t.id === targetId);
        if (!target) {
            return {
                success: false,
                message: '找不到指定的任务目标',
                isCompleted: false,
                currentProgress: 0
            };
        }

        const oldProgress = this.progress[targetId] || 0;
        const newProgress = Math.min(oldProgress + amount, target.count);
        this.progress[targetId] = newProgress;

        // 检查是否完成
        const isTargetCompleted = newProgress >= target.count;
        const isTaskCompleted = this.checkIfCompleted();

        if (isTaskCompleted) {
            this.complete();
        }

        this.updateEntity();

        return {
            success: true,
            message: `任务进度已更新：${target.description} (${newProgress}/${target.count})`,
            isCompleted: isTaskCompleted,
            currentProgress: newProgress
        };
    }

    /**
     * 完成任务
     */
    public complete(): CompleteResult {
        if (this.status !== TaskStatus.IN_PROGRESS) {
            return {
                success: false,
                message: '任务未在进行中',
                rewards: []
            };
        }

        if (!this.checkIfCompleted()) {
            return {
                success: false,
                message: '任务目标尚未完成',
                rewards: []
            };
        }

        this.status = TaskStatus.COMPLETED;
        this.completeTime = new Date();
        this.updateEntity();

        return {
            success: true,
            message: `任务 "${this.name}" 已完成`,
            rewards: this.rewards
        };
    }

    /**
     * 领取奖励
     */
    public claimRewards(): ClaimResult {
        if (this.status !== TaskStatus.COMPLETED) {
            return {
                success: false,
                message: '任务尚未完成',
                rewards: []
            };
        }

        this.status = TaskStatus.CLAIMED;
        this.updateEntity();

        return {
            success: true,
            message: `已领取任务 "${this.name}" 的奖励`,
            rewards: this.rewards
        };
    }

    /**
     * 重置任务（用于可重复任务）
     */
    public reset(): ResetResult {
        if (!this.isRepeatable) {
            return {
                success: false,
                message: '该任务不可重复'
            };
        }

        this.status = TaskStatus.NOT_STARTED;
        this.progress = {};
        this.startTime = undefined;
        this.completeTime = undefined;
        this.updateEntity();

        return {
            success: true,
            message: `任务 "${this.name}" 已重置`
        };
    }

    /**
     * 检查任务是否完成
     */
    private checkIfCompleted(): boolean {
        return this.targets.every((target, index) => {
            const progressKey = target.id || `target_${index}`;
            const progress = this.progress[progressKey] || 0;
            return progress >= target.count;
        });
    }

    /**
     * 检查是否满足任务要求
     */
    public checkRequirements(playerLevel: number, playerAttributes: Record<string, number>, completedTasks: string[]): RequirementCheckResult {
        const failedRequirements: string[] = [];

        // 检查等级要求
        if (playerLevel < this.requirements.level) {
            failedRequirements.push(`需要等级 ${this.requirements.level}`);
        }

        // 检查属性要求
        for (const [attr, required] of Object.entries(this.requirements.attributes)) {
            if ((playerAttributes[attr] || 0) < required) {
                failedRequirements.push(`需要 ${attr} ${required}`);
            }
        }

        // 检查前置任务要求
        for (const requiredTask of this.requirements.completedTasks) {
            if (!completedTasks.includes(requiredTask)) {
                failedRequirements.push(`需要完成任务：${requiredTask}`);
            }
        }

        return {
            canAccept: failedRequirements.length === 0,
            failedRequirements
        };
    }

    /**
     * 获取任务进度百分比
     */
    public getProgressPercentage(): number {
        if (this.targets.length === 0) return 100;

        let totalProgress = 0;
        let totalTargets = 0;

        this.targets.forEach((target, index) => {
            const progressKey = target.id || `target_${index}`;
            const progress = this.progress[progressKey] || 0;
            totalProgress += Math.min(progress, target.count);
            totalTargets += target.count;
        });

        return Math.round((totalProgress / totalTargets) * 100);
    }

    /**
     * 检查任务是否过期
     */
    public isExpired(): boolean {
        if (!this.deadline) return false;
        return new Date() > this.deadline;
    }

    /**
     * 获取剩余时间（毫秒）
     */
    public getRemainingTime(): number {
        if (!this.deadline) return -1;
        return Math.max(0, this.deadline.getTime() - Date.now());
    }

    /**
     * 验证任务数据
     */
    public validate(): any {
        const result = super.validate();

        if (!this.name || this.name.trim().length === 0) {
            result.errors.push({ field: 'name', message: '任务名称不能为空' });
        }

        if (this.targets.length === 0) {
            result.errors.push({ field: 'targets', message: '任务必须有至少一个目标' });
        }

        if (this.requirements.level < 1) {
            result.errors.push({ field: 'requirements.level', message: '等级要求必须大于0' });
        }

        result.isValid = result.errors.length === 0;
        return result;
    }
}

// 从统一枚举定义导入 (除了TaskTargetType)
import { TaskType, TaskStatus } from '../../core/rpg/types/task';
import type { TaskTargetType as CoreTaskTargetType } from '../../core/rpg/types/task';

// 重新导出以保持向后兼容
export { TaskType, TaskStatus };

/**
 * 任务目标接口
 */
export interface TaskTarget {
    id?: string;             // 目标ID（可选，兼容不同用法）
    type: TaskTargetType;    // 目标类型
    count: number;           // 目标数量
    current?: number;        // 当前进度（兼容RPG层）
    description: string;     // 目标描述
    targetId?: string;       // 目标ID（如怪物ID、道具ID等，兼容RPG层）
    data?: any;             // 目标数据
}

/**
 * 任务目标类型枚举
 */
export enum TaskTargetType {
    // 英文兼容
    KILL = 'kill',           // 击杀
    COLLECT = 'collect',     // 收集
    REACH = 'reach',         // 到达
    USE = 'use',             // 使用
    COMPLETE = 'complete',   // 完成
    CRAFT = 'craft',         // 制作
    
    // 中文兼容（RPG层）
    签到 = '签到',
    获得经验 = '获得经验',
    探索 = '探索',
    击杀怪物 = '击杀怪物'
}

/**
 * 任务奖励接口
 */
export interface TaskReward {
    type: RewardType | any;  // 奖励类型（兼容ItemType）
    id: string;             // 奖励ID（物品ID等）
    count: number;          // 奖励数量
    name?: string;          // 奖励名称（兼容RPG层）
    description?: string;    // 奖励描述（可选，兼容RPG层）
    data?: any;             // 奖励数据
}

/**
 * 奖励类型枚举
 */
export enum RewardType {
    EXPERIENCE = 'experience',    // 经验值
    ITEM = 'item',               // 物品
    CURRENCY = 'currency',       // 货币
    SKILL_POINT = 'skill_point', // 技能点
    ATTRIBUTE_POINT = 'attribute_point', // 属性点
    
    // 兼容ItemType枚举
    资源 = 'prop_资源',
    装备 = 'equipment',
    道具 = 'prop_道具',
    消耗品 = 'prop_消耗品',
}

/**
 * 任务要求接口
 */
export interface TaskRequirements {
    level: number;                      // 等级要求
    attributes: Record<string, number>; // 属性要求
    completedTasks: string[];           // 前置任务要求
}

/**
 * 任务优先级枚举
 */
export enum TaskPriority {
    LOW = 1,      // 低优先级
    NORMAL = 2,   // 普通优先级
    HIGH = 3,     // 高优先级
    URGENT = 4,   // 紧急优先级
}

/**
 * 重复类型枚举
 */
export enum RepeatType {
    NONE = 'none',        // 不重复
    DAILY = 'daily',      // 每日
    WEEKLY = 'weekly',    // 每周
    MONTHLY = 'monthly',  // 每月
    UNLIMITED = 'unlimited', // 无限制
}

/**
 * 任务数据接口
 */
export interface TaskData {
    [key: string]: any;
}

/**
 * 任务创建配置接口
 */
export interface TaskCreateConfig {
    id?: string;
    name: string;
    description?: string;
    type?: TaskType;
    status?: TaskStatus;
    targets?: TaskTarget[];
    rewards?: TaskReward[];
    requirements?: TaskRequirements;
    progress?: Record<string, number>;
    deadline?: Date;
    priority?: TaskPriority;
    tags?: string[];
    isMainQuest?: boolean;
    isRepeatable?: boolean;
    repeatType?: RepeatType;
    data?: TaskData;
    
    // 兼容Repository层
    startTime?: number;
    endTime?: number;
    completedTime?: number;
}

/**
 * 开始结果接口
 */
export interface StartResult {
    success: boolean;
    message: string;
}

/**
 * 进度结果接口
 */
export interface ProgressResult {
    success: boolean;
    message: string;
    isCompleted: boolean;
    currentProgress: number;
}

/**
 * 完成结果接口
 */
export interface CompleteResult {
    success: boolean;
    message: string;
    rewards: TaskReward[];
}

/**
 * 领取结果接口
 */
export interface ClaimResult {
    success: boolean;
    message: string;
    rewards: TaskReward[];
}

/**
 * 重置结果接口
 */
export interface ResetResult {
    success: boolean;
    message: string;
}

/**
 * 要求检查结果接口
 */
export interface RequirementCheckResult {
    canAccept: boolean;
    failedRequirements: string[];
}
